package com.example.geek.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.geek.R;
import com.example.geek.entity.LoginResponse;
import com.example.geek.entity.RegisterResponse;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    private EditText etAccount;
    private EditText etPwd;
    private Button btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        etAccount = findViewById(R.id.et_account);
        etPwd = findViewById(R.id.et_pwd);
        btnRegister = findViewById(R.id.btn_register);
        // 按钮监听器
        RegisterActivity.TextChange textChange = new RegisterActivity.TextChange();
        etAccount.addTextChangedListener(textChange);
        etPwd.addTextChangedListener(textChange);
        btnRegister.setEnabled(false);
        btnRegister.setBackgroundResource(R.drawable.shape_forbid_btn);
    }

    private void register(HashMap<String, Object> params) {
        // 注册接口
        OkHttpClient client = new OkHttpClient.Builder()
                .build();
        JSONObject jsonObject = new JSONObject(params);
        String jsonStr = jsonObject.toString();
        RequestBody requestBody = RequestBody.create(jsonStr, MediaType.parse("application/json;charset=utf-8"));
        Request request = new Request.Builder()
                .url("http://47.112.180.188:8080/renren-fast/app/register")
                .addHeader("contentType", "application/json;charset=utf-8")
                .post(requestBody)
                .build();
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", e.getMessage());
                Log.e("onFailure", e.toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String result = response.body().string();
                Gson gson = new Gson();
                RegisterResponse registerResponse = gson.fromJson(result,RegisterResponse.class);
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                if (registerResponse.getCode() == 500) {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "账号已存在", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                } else if (registerResponse.getCode() == 0){
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        });
    }

    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(etAccount.getText()) || TextUtils.isEmpty(etPwd.getText())) {
                btnRegister.setEnabled(false);
                btnRegister.setBackgroundResource(R.drawable.shape_forbid_btn);
            } else {
                btnRegister.setEnabled(true);
                btnRegister.setBackgroundResource(R.drawable.shape_login_btn);
                String account = etAccount.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("mobile", account);
                params.put("password", pwd);
                btnRegister.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        register(params);
                    }
                });
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}